package com.hboxs.asl.controller.app;

import com.gexin.fastjson.JSONObject;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.hboxs.asl.Constant;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.entity.Course;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Message;
import com.hboxs.asl.service.CourseService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.MessageService;
import com.hboxs.asl.util.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 个推
 */
@Controller("appPushController")
@RequestMapping("/app/push")
public class PushController extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "messageServiceImpl")
    private MessageService messageService;

    private static String appId = "Y349UCvnbc9a38H1XM9WE2";

    private static String appKey = "fULIXd9BCGAXgBiKbpfpL8";

    private static String masterSecret = "Sxu4upGnsoAXIGVM4hhAc2";

    private static String host = "http://sdk.open.api.igexin.com/apiex.htm";

    /**
     * 提问消息通知，老师回答通知
     * @param receiver 接收者
     * @param information
     */
    public static void notice(Member receiver, String information) {
        IGtPush push = new IGtPush(host, appKey, masterSecret);
        TransmissionTemplate transmissionTemplate = getTemplate(information);
        //推送ios
        SingleMessage iMessage = new SingleMessage();
        iMessage.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        iMessage.setOfflineExpireTime(24 * 3600 * 1000);
        iMessage.setData(transmissionTemplate);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        iMessage.setPushNetWorkType(0);
        //个推
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(receiver.getClientId());

        try {
            push.pushMessageToSingle(iMessage, target);
        } catch (RequestException e) {
            e.printStackTrace();
            push.pushMessageToSingle(iMessage, target, e.getRequestId());
        }
    }

//    /**
//     * 设置跳转类型
//     * @param receiver 接收者
//     * @param information
//     */
//    public static void noticeTest(Member receiver, String information, Long id, String type) {
//        IGtPush push = new IGtPush(host, appKey, masterSecret);
//
//        //TODO 个推json
//        Map<String,Object> mapObject=new HashMap<>();
//        mapObject.put("title", "易经应用");
//        mapObject.put("content", information);
//        mapObject.put("id", id);
//        mapObject.put("type", type);
//        JSONObject jsonObject = new JSONObject(mapObject);
//
//        TransmissionTemplate transmissionTemplate = getTemplate(jsonObject.toJSONString());
//        //推送ios
//        SingleMessage iMessage = new SingleMessage();
//        iMessage.setOffline(true);
//        // 离线有效时间，单位为毫秒，可选
//        iMessage.setOfflineExpireTime(24 * 3600 * 1000);
//        iMessage.setData(transmissionTemplate);
//        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
//        iMessage.setPushNetWorkType(0);
//        //个推
//        Target target = new Target();
//        target.setAppId(appId);
//        target.setClientId(receiver.getClientId());
//
//        try {
//            push.pushMessageToSingle(iMessage, target);
//        } catch (RequestException e) {
//            e.printStackTrace();
//            push.pushMessageToSingle(iMessage, target, e.getRequestId());
//        }
//    }


    /**
     * 个推
     * @param courseId
     * @param information
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage Push(Long courseId, String information) throws Exception {
        try {
            Member teacher = memberService.getCurrentByToken();
            if (teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Course course = courseService.find(courseId);
            if (course == null) {
                return JsonMessage.error("预告不存在");
            }

            String messageTemplate = information;
//            if (course.getDatePattern() != null) {
//                messageTemplate += ",视频开播时间为：" + DateUtils.dateToStr(course.getDatePattern());
//            }

            //获取我的粉丝
            Set<Member> memberSet = teacher.getFavorMembers();
            if (memberSet.size() > 1) {
                IGtPush push = new IGtPush(host, appKey, masterSecret);
//                //TODO 个推json
//                Map<String,Object> mapObject=new HashMap<>();
//                mapObject.put("title", "易经应用");
//                mapObject.put("content", messageTemplate);
//                mapObject.put("type", Constant.GETUI_COURSE);
//                mapObject.put("id", courseId);
//                JSONObject obj=new JSONObject(mapObject);

                TransmissionTemplate transmissionTemplate = getTemplate(messageTemplate);

                //推送ios
                SingleMessage iMessage = new SingleMessage();
                iMessage.setOffline(true);
                // 离线有效时间，单位为毫秒，可选
                iMessage.setOfflineExpireTime(24 * 3600 * 1000);
                iMessage.setData(transmissionTemplate);
                // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
                iMessage.setPushNetWorkType(0);

                for (Member member : memberSet) {
                    //保存我的信息
                    Message message1 = new Message();
                    message1.setId(null);
                    message1.setContent(information);
                    message1.setMosaicContent(messageTemplate);
                    message1.setSender(teacher);
                    message1.setReceiver(member);
                    message1.setTitle("易经应用");

                    //个推
                    Target target = new Target();
                    target.setAppId(appId);
                    target.setClientId(member.getClientId());

                    try {
                        push.pushMessageToSingle(iMessage, target);
                    } catch (RequestException e) {
                        e.printStackTrace();
                        push.pushMessageToSingle(iMessage, target, e.getRequestId());
                    }
                    messageService.save(message1);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.success();
    }

    public static TransmissionTemplate getTemplate(String msg) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(msg);
        template.setTransmissionType(2);
        APNPayload payload = new APNPayload();
        //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
        payload.setAutoBadge("+1");
        payload.setContentAvailable(1);
        payload.setSound("default");
        payload.setCategory("$由客户端定义");

        //简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg("hello"));

        //字典模式使用APNPayload.DictionaryAlertMsg
        payload.setAlertMsg(getDictionaryAlertMsg(msg));

        template.setAPNInfo(payload);
        return template;
    }

    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String msg) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(msg);
        alertMsg.setActionLocKey("ActionLockey");
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image");
        // iOS8.2以上版本支持
        alertMsg.setTitle("");
        alertMsg.setTitleLocKey("");
        alertMsg.addTitleLocArg("");
        return alertMsg;
    }

}


